package com.hh.config;

import feign.RequestInterceptor;
import feign.RequestTemplate;
import org.springframework.context.annotation.Configuration;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;

/**
 * @author 辉辉 2022/8/14 17:35
 * token传递问题
 * 远程调用的拦截
 */
@Configuration
public class OpenFeignInterceptor implements RequestInterceptor {
    /**
     * 在这里做token的传递
     * 1. 浏览器到A服务 -> B服务
     * 2. mq直接发起远程调用 是没有前置request的
     * 3. 支付宝回调 有request 但是没有token
     *
     * @param requestTemplate 发起远程调用的请求
     */
    @Override
    public void apply(RequestTemplate requestTemplate) {
        // 是从浏览器带过来的 request 肯定有token
        ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        if (requestAttributes != null) {
            // 有请求 是我们前端的请求 2. 可能是其他系统的回调 那么有request但是没有token
            HttpServletRequest request = requestAttributes.getRequest();
            if (!ObjectUtils.isEmpty(request)) {
                String authorization = request.getHeader("Authorization");
                if (!StringUtils.isEmpty(authorization)) {
                    // 往新的请求内放 做一个传递
                    requestTemplate.header("Authorization", authorization);
                }
            }
        }
        // 都是没有token的 比如mq的自发调用 其他应用的回调
        requestTemplate.header("Authorization", "bearer eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCJ9.eyJzY29wZSI6WyJyZWFkIl0sImV4cCI6MzgwNzk2Nzc0MywianRpIjoiZWY3NjAyNmEtM2IwOS00NjM5LThjN2YtMjBmYzcwNzBiZTUxIiwiY2xpZW50X2lkIjoiY2xpZW50In0.UjtS3IPS6FlBEsCGbhJXbI_bgAWozZoOzCDUPLWuyQj-am4VGHu0BVbdJxdTHpNu1mk5LSkFsdHmN3vjn7FokG8Y48wMFSw056p-Xkie3arVtYRs5MyZtvmK8UV1bOD0VW1ilO7cINs9qIZy3gDNqFriMAm-SXSTf-lwJRVzWqu0uaRnc_l2C_e6_1LNHR-vWOGZPMGCm3PudgtaA4m1ikq_ZOCXixbupblY3Twkn8NUaUyR4dWU21LefsnmHdAngskeyOUKj25UqeZd7vx9N9y63s2fCae1NO3kNq8ozAr1tBcsccpHO6wpyAlBoJ9ea26PEC3w5Nqr3Ov2_pQcBw");
    }
}
